package com.truyentranh.modules.truyentranh;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.truyentranh.R;
import com.truyentranh.controls.AdsViewControl;
import com.truyentranh.controls.DataCachedControl;
import com.truyentranh.data.TamDiemDetailModuleData;
import com.truyentranh.main.AdsBussiness;
import com.truyentranh.modules.tamdiem.TamDiemDetailModulesRenderAdapter;
import com.truyentranh.network.APIRequestWorker;
import com.truyentranh.network.Request;
import com.truyentranh.network.RequestListener;
import com.truyentranh.requester.TruyenTranhRequester;
import com.truyentranh.utils.AppSettingParams;
import com.truyentranh.utils.Logger;

public class TruyenTranhDetailCategoryActivity extends Activity implements OnScrollListener, RequestListener, OnItemClickListener {

	LinearLayout loadingPage = null;
	LinearLayout loadingError = null;

	LinearLayout mainContent = null;
	AdsViewControl prviewTamDiem = null;
	LinearLayout loadingMore = null;
	GridView imageListView = null;

	TamDiemDetailModulesRenderAdapter tamDiemRenderAdapter = null;
	String idModules = "";
	String nameTitle = "";
	boolean isLoading = false;

	long requestId = -1;
	int MAX_COUNT = 20;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);

		Bundle extras = getIntent().getExtras();

		if (extras != null) {
			idModules = extras.getString("ID");
			nameTitle = extras.getString("NAME");

			Logger.logMe("id = " + idModules);
		}
		// Remove notification bar
		this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
		setContentView(R.layout.tamdiem_detail_module_activity_layout);
		init();

		loadingPage = (LinearLayout) findViewById(R.id.loadingpagetamdiem);
		loadingError = (LinearLayout) findViewById(R.id.loadingError);
		loadingMore = (LinearLayout) findViewById(R.id.loadMore);
		loadingError.setVisibility(View.INVISIBLE);

		mainContent = (LinearLayout) findViewById(R.id.mainContent);

		prviewTamDiem = (AdsViewControl) findViewById(R.id.prviewTamDiem);
		imageListView = (GridView) findViewById(R.id.imageListView);

		imageListView.setNumColumns(3);

		TextView textView = (TextView) findViewById(R.id.titleActivity);
		textView.setText(nameTitle);

		Button button = (Button) findViewById(R.id.btnMoreFunctions);

		button.setBackgroundResource(android.R.drawable.ic_search_category_default);
		button.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				Intent itent = new Intent(TruyenTranhDetailCategoryActivity.this, TruyenTranhSearchActivity.class);
				startActivity(itent);
			}
		});

		Button back = (Button) findViewById(R.id.btnBackAcvitity);
		if (back != null) {
			back.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					requestId = -1;
					DataCachedControl.getInstance().clearCached(DataCachedControl.TRUYENTRANH_CATEGORY_DETAIL);
					finish();
				}
			});
		}
	}

	void doAdsByServer() {
		AdsBussiness.getInstance().doGetAdsFromServer(this, prviewTamDiem);
	}

	@Override
	protected void onDestroy() {
		APIRequestWorker.getInstance().clearAllRequests();
		DataCachedControl.getInstance().clearCached(DataCachedControl.TRUYENTRANH_CATEGORY_DETAIL);
		super.onDestroy();
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
			requestId = -1;
			DataCachedControl.getInstance().clearCached(DataCachedControl.TRUYENTRANH_CATEGORY_DETAIL);
			finish();
			return true;
		}

		return super.onKeyDown(keyCode, event);
	}

	boolean isStart = true;

	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		super.onStart();
		if (isStart) {
			isStart = false;
			onStartUp();
		} else {
			doAdsByServer();
		}
	}

	int page = 1;

	private void onStartUp() {

		loadingPage.setVisibility(View.VISIBLE);

		loadingError.setVisibility(View.INVISIBLE);
		loadingMore.setVisibility(View.INVISIBLE);
		loadingError.setVisibility(View.INVISIBLE);
		mainContent.setVisibility(View.INVISIBLE);
		prviewTamDiem.setVisibility(View.VISIBLE);
		imageListView.setVisibility(View.INVISIBLE);

		ArrayList<TamDiemDetailModuleData> cachedList = (ArrayList<TamDiemDetailModuleData>) DataCachedControl.getInstance().getCached(DataCachedControl.TRUYENTRANH_CATEGORY_DETAIL);
		if (cachedList != null && !cachedList.isEmpty()) {
			fillDatatoGridView(cachedList);
			
		} else {
			TruyenTranhRequester requester = TruyenTranhRequester.detailCategory(idModules, page, MAX_COUNT, TruyenTranhDetailCategoryActivity.this);
			requestId = AppSettingParams.nextRequestId();
			requester.setRequestId(requestId);
			APIRequestWorker.getInstance().addAPIRequest(requester);
		}
	}

	void init() {
	}

	void fillDatatoGridView(final ArrayList<TamDiemDetailModuleData> requestedDataList) {

		if (imageListView != null) {
			runOnUiThread(new Runnable() {

				@Override
				public void run() {
					DataCachedControl.getInstance().putCached(DataCachedControl.TRUYENTRANH_CATEGORY_DETAIL, new ArrayList<TamDiemDetailModuleData>(requestedDataList));
					if (tamDiemRenderAdapter == null) {
						tamDiemRenderAdapter = new TamDiemDetailModulesRenderAdapter(TruyenTranhDetailCategoryActivity.this, 1, 1, requestedDataList);
						imageListView.setAdapter(tamDiemRenderAdapter);
					} else {
						tamDiemRenderAdapter.setBlockList(requestedDataList);
						tamDiemRenderAdapter.notifyDataSetChanged();
					}

					imageListView.setOnItemClickListener(TruyenTranhDetailCategoryActivity.this);
					imageListView.setOnScrollListener(TruyenTranhDetailCategoryActivity.this);

					loadingPage.setVisibility(View.GONE);
					loadingError.setVisibility(View.GONE);
					loadingMore.setVisibility(View.GONE);

					mainContent.setVisibility(View.VISIBLE);
					prviewTamDiem.setVisibility(View.VISIBLE);
					imageListView.setVisibility(View.VISIBLE);

					isLoading = false;
					
					doAdsByServer();
				}
			});

		}
	}

	@Override
	public void onRequestComplete(final Request request) {
		Logger.logMe("requestId = " + requestId);

		if (request instanceof TruyenTranhRequester) {
			TruyenTranhRequester r = (TruyenTranhRequester) request;

			ArrayList<TamDiemDetailModuleData> requestedDataList = new ArrayList<TamDiemDetailModuleData>();
			try {
				JSONObject jsonObject = r.getData();

				JSONArray jsonArray = jsonObject.getJSONArray("data");
				final int size = jsonArray.length();
				for (int i = 0; i < size; i++) {
					JSONObject datas = jsonArray.getJSONObject(i);

					String title = datas.has(TamDiemDetailModuleData.TITLE) ? datas.getString(TamDiemDetailModuleData.TITLE) : "";
					String avatar = datas.has(TamDiemDetailModuleData.AVATAR) ? datas.getString(TamDiemDetailModuleData.AVATAR) : "";
					String href = datas.has(TamDiemDetailModuleData.HREF) ? datas.getString(TamDiemDetailModuleData.HREF) : "";

					TamDiemDetailModuleData detailModuleData = new TamDiemDetailModuleData(title, avatar, href);
					requestedDataList.add(detailModuleData);
				}

			} catch (Exception e) {

			}

			fillDatatoGridView(requestedDataList);
		}
	}

	@Override
	public void onRequestFailed(String errorMsg, Request request) {
		if (request instanceof TruyenTranhRequester && requestId == request.getRequestId()) {
			runOnUiThread(new Runnable() {

				@Override
				public void run() {
					loadingPage.setVisibility(View.GONE);
					loadingError.setVisibility(View.VISIBLE);
					loadingMore.setVisibility(View.GONE);

					mainContent.setVisibility(View.GONE);
					imageListView.setVisibility(View.GONE);

					isLoading = false;
					doAdsByServer();
				}
			});
		}
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int index, long arg3) {
		Logger.logMe("1");
		if (tamDiemRenderAdapter != null) {
			Logger.logMe("2");
			TamDiemDetailModuleData diemMetalData = tamDiemRenderAdapter.getItem(index);
			Logger.logMe("3");

			final String href = diemMetalData.getHref();
			if (href != null && !"".equals(href)) {
				Intent intent = new Intent(getApplication(), TruyenTranhChapterListActivity.class);
				intent.putExtra("href", href);
				intent.putExtra("NAME", diemMetalData.getTitle());
				intent.putExtra("AVATAR", diemMetalData.getAvatar());
				TruyenTranhSession.setCurrentComic(diemMetalData);
				
				startActivity(intent);
			}
		}
	}

	RequestListener listenerLoadMore = new RequestListener() {

		@Override
		public void onRequestFailed(String errorMsg, Request request) {
			runOnUiThread(new Runnable() {

				@Override
				public void run() {
					// TODO Auto-generated method stub
					if (loadingMore != null && loadingMore.getVisibility() != View.GONE)
						loadingMore.setVisibility(View.GONE);
				}
			});

		}

		@Override
		public void onRequestComplete(Request request) {
			if (request instanceof TruyenTranhRequester) {

				TruyenTranhRequester r = (TruyenTranhRequester) request;

				final ArrayList<TamDiemDetailModuleData> requestedDataList = new ArrayList<TamDiemDetailModuleData>();
				try {
					JSONObject jsonObject = r.getData();

					JSONArray jsonArray = jsonObject.getJSONArray("data");
					final int size = jsonArray.length();
					for (int i = 0; i < size; i++) {
						JSONObject datas = jsonArray.getJSONObject(i);

						String title = datas.has(TamDiemDetailModuleData.TITLE) ? datas.getString(TamDiemDetailModuleData.TITLE) : "";
						String avatar = datas.has(TamDiemDetailModuleData.AVATAR) ? datas.getString(TamDiemDetailModuleData.AVATAR) : "";
						String href = datas.has(TamDiemDetailModuleData.HREF) ? datas.getString(TamDiemDetailModuleData.HREF) : "";

						TamDiemDetailModuleData detailModuleData = new TamDiemDetailModuleData(title, avatar, href);
						requestedDataList.add(detailModuleData);
					}
				} catch (Exception e) {

				}

				if (imageListView != null) {
					runOnUiThread(new Runnable() {

						@Override
						public void run() {
							if (tamDiemRenderAdapter != null) {

								ArrayList<TamDiemDetailModuleData> cachedList = (ArrayList<TamDiemDetailModuleData>) DataCachedControl.getInstance().getCached(DataCachedControl.TRUYENTRANH_CATEGORY_DETAIL);
								if (cachedList != null && requestedDataList != null) {
									final int size = requestedDataList.size();
									for (int i = 0; i < size; i++) {
										cachedList.add(requestedDataList.get(i));
									}
								}
								tamDiemRenderAdapter.appendData(requestedDataList);
							}

							if (!requestedDataList.isEmpty())
								isLoading = false;

							if (loadingMore != null && loadingMore.getVisibility() != View.GONE)
								loadingMore.setVisibility(View.GONE);
						}
					});

				}
			}

		}
	};

	@Override
	public void onScroll(AbsListView arg0, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
		int lastInScreen = firstVisibleItem + visibleItemCount;
		if (!isLoading && tamDiemRenderAdapter != null && !tamDiemRenderAdapter.isEmpty() && (lastInScreen == totalItemCount) && (page < 100)) {
			if (loadingMore != null && loadingMore.getVisibility() != View.VISIBLE)
				loadingMore.setVisibility(View.VISIBLE);
			isLoading = true;
			page += 1;

			TruyenTranhRequester requester = TruyenTranhRequester.detailCategory(idModules, page, MAX_COUNT, listenerLoadMore);
			APIRequestWorker.getInstance().addAPIRequest(requester);
		}
	}

	@Override
	public void onScrollStateChanged(AbsListView view, int scrollState) {
		// TODO Auto-generated method stub

	}
}
